#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>

#include "Acceptor.h"
#include "Logger.h"
#include "InetAddress.h"

static int createNonblocking()
{
    int sockfd = ::socket(AF_INET,SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,0);
    if(sockfd<0)
    {
        LOG_FATAL("%s:%s:%d listen socket create error:%d \n",__FILE__,__FUNCTION__,__LINE__,errno);
    }
    return sockfd;
}

Acceptor::Acceptor(EventLoop* loop,const InetAddress& listenAddr,bool reuseport)
    : loop_(loop)
    // 此处 createNonblocking() 和 acceptSocket_.fd() 是一个东西
    , acceptSocket_(createNonblocking())
    , acceptChannel_(loop,acceptSocket_.fd()) 
    , listening_(false)
{
    acceptSocket_.setReuseAddr(true);
    acceptSocket_.setReusePort(true);
    acceptSocket_.bindAddress(listenAddr);
    // 有新用户链接 执行回调
    acceptChannel_.setReadCallback(std::bind(&Acceptor::handleRead,this));

}
Acceptor::~Acceptor()
{
    acceptChannel_.disableAll();
    acceptChannel_.remove();
}


void Acceptor::handleRead()
{
    InetAddress peerAddr;
    int connfd = acceptSocket_.accept(&peerAddr);

    if(connfd>=0)
    {
        if(newConnectionCallback_)
        {
             // 调用新连接回调 传递套接字和客户端地址
            newConnectionCallback_(connfd,peerAddr);
        }
        else
        {
            // 若无回调 直接关闭连接（避免资源泄漏）
            ::close(connfd);
        }
    }
    else
    {
        LOG_FATAL("%s:%s:%d accept error:%d \n",__FILE__,__FUNCTION__,__LINE__,errno);
    }
}

void Acceptor::listen()
{
    listening_=true;
    acceptSocket_.listen();
    acceptChannel_.enableReading();
}